package org.evelsoft.common.utils;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.Entity;

/**
 *
 * @author wojtek
 */
public class Logger {

	public final static String START = "START";
	public final static String STOP = "END";
	private final static String EJB_STATELESS = "EJB-Stateless";
	private final static String EJB_STATEFUL = "EJB-Stateful";
	private final static String EJB_ENTITY = "EJB-Entity";
	private final static String EJB_OTHER = "EJB";
	private final static String DELIMITER = ";";
	private static Map<Class, Logger> map = new HashMap<Class, Logger>();
	private Map<String, Long> invokedMethods = new Hashtable<String, Long>();
	private final String beanType;

	private Logger(Class clazz) {
		if (clazz.getAnnotation(Stateless.class) != null) {
			beanType = EJB_STATELESS;
		} else if (clazz.getAnnotation(Stateful.class) != null) {
			beanType = EJB_STATEFUL;
		} else if (clazz.getAnnotation(Entity.class) != null) {
			beanType = EJB_ENTITY;
		} else {
			beanType = EJB_OTHER;
		}
	}

	public static synchronized Logger getInstance(Class clazz) {
		Logger log = map.get(clazz);
		if (log == null) {
			log = new Logger(clazz);
			map.put(clazz, log);
		}
		return log;
	}

	public void debug(String action, String message) {
		Thread currentThread = Thread.currentThread();
		StackTraceElement ste = currentThread.getStackTrace()[0];
		System.out.println(currentThread.getStackTrace().toString());
		Long time = System.currentTimeMillis();
		String invokeSignature = new String(currentThread.getId() + ste.getClassName());
		if (Logger.START.equals(action)) {
			invokedMethods.put(invokeSignature, time);
			System.out.println(beanType + DELIMITER + START + "-" + 0 + DELIMITER + ste.getMethodName() + DELIMITER + message + DELIMITER + currentThread.getId());
		} else if (Logger.STOP.equals(action)) {
			Long started = invokedMethods.remove(invokeSignature);
			System.out.println(beanType + DELIMITER + STOP + "-" + (time - started) + DELIMITER + ste.getMethodName() + DELIMITER + message + DELIMITER + currentThread.getId());
		} else {
			System.out.println(beanType + DELIMITER + ste.getMethodName() + DELIMITER + message + DELIMITER + currentThread.getId()
					+ DELIMITER);
		}
	}

	public void debug(Exception ex) {
		ex.printStackTrace();
	}
}
